package com.cjy.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import com.base.common.enums.LogCategory;
import com.base.common.persistent.dao.*;
import com.base.common.persistent.model.TLog;
import com.ygj.easemob.server.example.api.ChatGroupAPI;
import com.ygj.easemob.server.example.comm.body.ChatGroupBody;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.enums.AppType;
import com.base.common.persistent.model.Employee;
import com.base.common.persistent.model.Terminal;
import com.base.common.persistent.model.User;
import com.base.common.utils.EasyUtil;
import com.cjy.user.service.UserService;
import com.ygj.easemob.server.example.api.IMUserAPI;
import com.ygj.easemob.server.example.comm.ClientContext;
import com.ygj.easemob.server.example.comm.EasemobRestAPIFactory;
import com.ygj.easemob.server.example.comm.body.IMUserBody;
import com.ygj.easemob.server.example.comm.wrapper.BodyWrapper;

/**
 * userService的实现类
 * 
 * @author kat.luhongkai
 * 
 */

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private TerminalMapper terminalMapper;

	@Resource
	private TsmsSendCacheMapper tsmsSendCacheMapper;

	@Resource
	private UserMapper userMapper;

	@Resource
	private EmployeeMapper employeeMapper;

	@Resource
	private EasyUtil easyUtil;

    @Resource
    private TLogMapper tLogMapper;

	/**
	 * 获取六位数的验证码
	 * 
	 * @return
	 */
	public int getSixCaptcha() {
		Random rand = new Random();
		int captcha = Math.abs(rand.nextInt()) % (999999 - 100000 + 1) + 100000;
		return captcha;
	}

	/**
	 * 城际云android设备获取验证码，准备注册
	 * 
	 * @return
	 */
	@Override
	@Transactional
	public int androidGetCaptcha(Terminal terminal) {
		int result = 0;
		int captcha = getSixCaptcha(); // 验证码生成
		terminal.setCaptcha(captcha); // 设置用户验证码

		List<Terminal> terminals = new ArrayList<Terminal>();

		// 判断安卓设备是否已经注册或被拉入黑名单
		terminals = terminalMapper.queryTerminalByCodesRegisted(null, null,
				terminal.getCode(), AppType.CJY.getValue());
		if (terminals.size() > 0) {
			result = 2;
		} else {

			// 判断手机号是否已经注册
			terminals = terminalMapper.queryTerminalByPhoneRegisted(terminal
					.getPhone().trim(), AppType.CJY.getValue());
			if (terminals.size() > 0) {

				// 判断注册的手机号是否已经绑定设备码
				if (terminals.get(0).getCode() == null
						|| terminals.get(0).getCode().trim() == "") {

					// 绑定设备码
					terminal.setId(terminals.get(0).getId());
					if (terminalMapper.updateTerminalById(terminal) > 0) {
						result = 1;
					} else {
						result = 0;
					}
				} else {
					result = 3;
				}
			} else {
				terminal.setStatus(0); // 设置状态码，默认为0（未通过）

				// 判断该微信是否已经获取过验证码，处于未注册状态
				terminals = terminalMapper
						.queryTerminalByCodesOrPhoneNotRegisted(null, null,
								terminal.getCode(), null,
								AppType.CJY.getValue());
				if (terminals.size() > 0) {
					// 更新设备信息
					terminal.setId(terminals.get(0).getId());
					result = terminalMapper.updateTerminalById(terminal);
				} else if ((terminals = terminalMapper
						.queryTerminalByCodesOrPhoneNotRegisted(null, null,
								null, terminal.getPhone(),
								AppType.CJY.getValue())).size() > 0) {

					// 绑定设备码
					if (terminalMapper.updateTerminalById(terminal) > 0) {
						result = 1;
					} else {
						result = 0;
					}
				} else {
					// 新增微信设备
					terminal.setBid(AppType.CJY.getValue());
					result = terminalMapper.addTerminal(terminal);
				}
			}
		}
		if (result == 1) {
			easyUtil.sendSms("验证码：" + captcha, terminal.getPhone());
		}

		return result;
	}

	/**
	 * 城际云ios设备获取验证码，准备注册
	 * 
	 * @return
	 */
	@Override
	@Transactional
	public int iosGetCaptcha(Terminal terminal) {
		int result = 0;
		int captcha = getSixCaptcha(); // 验证码生成
		terminal.setCaptcha(captcha); // 设置用户验证码

		List<Terminal> terminals = new ArrayList<Terminal>();

		// 判断ios设备是否已经注册或被拉入黑名单
		terminals = terminalMapper.queryTerminalByCodesRegisted(null, terminal
				.getAppleId().trim(), null, AppType.CJY.getValue());
		if (terminals.size() > 0) {
			result = 2;
		} else {

			// 判断手机号是否已经注册
			terminals = terminalMapper.queryTerminalByPhoneRegisted(terminal
					.getPhone().trim(), AppType.CJY.getValue());
			if (terminals.size() > 0) {

				// 判断注册的手机号是否已经绑定设备码
				if (terminals.get(0).getAppleId() == null
						|| terminals.get(0).getAppleId().trim() == "") {

					// 绑定设备码
					terminal.setId(terminals.get(0).getId());
					if (terminalMapper.updateTerminalById(terminal) > 0) {
						result = 1;
					} else {
						result = 0;
					}
				} else {
					result = 3;
				}
			} else {
				terminal.setStatus(0); // 设置状态码，默认为0（未通过）

				// 判断该微信是否已经获取过验证码，处于未注册状态
				terminals = terminalMapper
						.queryTerminalByCodesOrPhoneNotRegisted(null,
								terminal.getAppleId(), null, null,
								AppType.CJY.getValue());
				if (terminals.size() > 0) {
					// 更新设备信息
					terminal.setId(terminals.get(0).getId());
					result = terminalMapper.updateTerminalById(terminal);
				} else if ((terminals = terminalMapper
						.queryTerminalByCodesOrPhoneNotRegisted(null, null,
								null, terminal.getPhone().trim(),
								AppType.CJY.getValue())).size() > 0) {

					// 绑定设备码
					if (terminalMapper.updateTerminalById(terminal) > 0) {
						result = 1;
					} else {
						result = 0;
					}
				} else {
					// 新增微信设备
					terminal.setBid(AppType.CJY.getValue());
					result = terminalMapper.addTerminal(terminal);
				}
			}
		}
		if (result == 1) {
			easyUtil.sendSms("验证码：" + captcha, terminal.getPhone());
		}

		return result;
	}

	/**
	 * 微信设备获取验证码，准备注册
	 * 
	 * @param terminal
	 * @return
	 */
	@Override
	@Transactional
	public int weChatGetCaptcha(Terminal terminal) {

		int result = 1;
		int captcha = getSixCaptcha(); // 验证码生成
		terminal.setCaptcha(captcha); // 设置用户验证码

		List<Terminal> terminals = new ArrayList<Terminal>();

		// 判断微信设备是否已经注册或被拉入黑名单
		terminals = terminalMapper.queryTerminalByCodesRegisted(terminal
				.getOpenId().trim(), null, null, AppType.CJY.getValue());
		if (terminals.size() > 0) {
			result = 2;
		} else {
			// 判断手机号是否已经注册
			terminals = terminalMapper.queryTerminalByPhoneRegisted(terminal
					.getPhone().trim(), AppType.CJY.getValue());
			if (terminals.size() > 0) {

				// 判断注册的手机号是否已经绑定微信号
				if (terminals.get(0).getOpenId() == null
						|| terminals.get(0).getOpenId().trim() == "") {
					// 绑定微信号
					terminal.setId(terminals.get(0).getId());
					if (terminalMapper.updateTerminalById(terminal) > 0) {
						result = 1;
					} else {
						result = 0;
					}
				} else {
					result = 3;
				}
			} else {
				terminal.setStatus(0); // 设置状态码，默认为0（未通过）

				// 判断该微信是否已经获取过验证码，处于未注册状态
				terminals = terminalMapper
						.queryTerminalByCodesOrPhoneNotRegisted(
								terminal.getOpenId(), null, null, null,
								AppType.CJY.getValue());
				if (terminals.size() > 0) {
					// 更新设备信息
					terminal.setId(terminals.get(0).getId());
					return terminalMapper.updateTerminalById(terminal);
				} else if (terminalMapper
						.queryTerminalByCodesOrPhoneNotRegisted(null, null,
								null, terminal.getPhone(),
								AppType.CJY.getValue()).size() > 0) {
					result = 3;
				} else {
					// 新增微信设备
					result = terminalMapper.addTerminal(terminal);
				}
			}
		}
		if (result == 1) {
			easyUtil.sendSms("验证码：" + captcha, terminal.getPhone());
		}
		return result;
	}

	@Transactional
	@Override
	public int registe(Terminal terminal) {
		int result = 1;
		if ((terminal.getPhone() != null && terminal.getPhone().trim() != "")
				&& ((terminal.getCode() != null && terminal.getCode().trim() != "")
						|| (terminal.getOpenId() != null && terminal
								.getOpenId().trim() != "") || (terminal
						.getAppleId() != null && terminal.getAppleId().trim() != ""))) {

			List<Terminal> terminals = new ArrayList<Terminal>();

			if (terminal.getBid() == 0) {
				terminals = terminalMapper
						.queryTerminalByCodesAndPhoneNotRegisted(null, null,
								terminal.getCode(), terminal.getPhone(),
								AppType.CJY.getValue());
			} else if (terminal.getBid() == 2) {
				terminals = terminalMapper
						.queryTerminalByCodesAndPhoneNotRegisted(
								terminal.getOpenId(), null, null,
								terminal.getPhone(), AppType.CJY.getValue());
			} else {
				terminals = terminalMapper
						.queryTerminalByCodesAndPhoneNotRegisted(null,
								terminal.getAppleId(), null,
								terminal.getPhone(), AppType.CJY.getValue());
			}

			// 判断验证码是否正确
			if (terminal.getCaptcha() != terminals.get(0).getCaptcha()) {
				return 2;
			}

			// 查询当前手机好是否在用户档案中已经存在，存在则在中间表中添加对应记录
			List<User> users = userMapper.queryUserByPhone(terminal.getPhone()
					.trim());
			terminal.setId(terminals.get(0).getId());
			if (users.size() > 0) {

				// 用户档案中存在该手机号，设置设备信息状态为有效状态
				terminal.setStatus(1);
				// 判断是微信注册还是app注册
				terminalMapper.updateTerminalById(terminal);
				for (User user : users) {
					userMapper.addUserInfo(user.getId(), terminals.get(0)
							.getId());
				}
			} else {
				
				// 用户档案中不存在该手机记录，更新设备信息为申请状态
				terminal.setStatus(3);
				System.out.println(terminalMapper.updateTerminalById(terminal));
				return 3;
			}
		} else {
			return 0;
		}
		return result;
	}

	@Override
	public List login(Terminal terminal) {
		List list = new ArrayList();
		try {

			List<Terminal> terminals = new ArrayList<Terminal>();

			// 判断登录设备
			if (terminal.getBid() == 0 || terminal.getBid() == 3
					|| terminal.getBid() == 2) {

				// 设置手机号
				if (terminal.getBid() == 0) {
					terminals = terminalMapper.queryTerminalByCodesRegisted(
							null, null, terminal.getCode(),
							AppType.CJY.getValue());
				} else if (terminal.getBid() == 2) {
					terminals = terminalMapper.queryTerminalByCodesRegisted(
							terminal.getOpenId(), null, null,
							AppType.CJY.getValue());
				} else {
					terminals = terminalMapper.queryTerminalByCodesRegisted(
							null, terminal.getAppleId(), null,
							AppType.CJY.getValue());
				}

				terminal.setBid(AppType.CJY.getValue());
				list = userMapper.login(terminal);

				for (Object user : list) {
					((User) user).setPhone(terminals.get(0).getPhone());
				}
			} else {
                int bid = terminal.getBid();
                if (bid == 1 || bid == 5) {
                    terminals = terminalMapper.queryTerminalByCodesRegisted(
                            null, null, terminal.getCode(),
                            AppType.YGJ.getValue());
                } else if (bid == 4 || bid == 6) {
                    terminals = terminalMapper.queryTerminalByCodesRegisted(
                            null, terminal.getAppleId(), null,
                            AppType.YGJ.getValue());
                }
				terminal.setBid(AppType.YGJ.getValue());
				list = employeeMapper.employeeLogin(terminal);
				if (list.size() > 0) {
					TLog tLog = new TLog();
					tLog.setAppType(bid);
					tLog.setContent("用户：" + terminals.get(0).getPhone() + "执行登录操作");
					tLog.setTerminalId((long) terminals.get(0).getId());
					tLog.setCategory(LogCategory.LOGIN.getValue());
					tLogMapper.insertSelective(tLog);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return list;
		}
		return list;
	}

	/**
	 * @param terminal
	 * @return
	 */
	/*
	 * @Transactional public List userLogin(Terminal terminal, List list) {
	 * if(terminal.getBid() == 2) {
	 * 
	 * } else { } for(Object user : list) {
	 * ((User)user).setPhone(terminal.getPhone()); } return list; }
	 *//**
	 * 员工登录
	 * 
	 * @param terminal
	 * @return
	 */
	/*
	 * @Transactional public List employeeLogin(Terminal terminal, List list) {
	 * 
	 * for(Object employee : list) { ((Employee)
	 * employee).setPhone(terminal.getPhone()); } return list; }
	 */

	@Override
	public int managerRegiste(Terminal terminal) {

		// 判断设备是否已经注册或被拉入黑名单
		int result = 0;
		List<Terminal> terminals = new ArrayList<Terminal>();

		if (terminal.getBid() == 1) {
			terminals = terminalMapper.queryTerminalByCodesRegisted(null, null,
					terminal.getCode(), AppType.YGJ.getValue());
		} else {
			terminals = terminalMapper.queryTerminalByCodesRegisted(null,
					terminal.getAppleId(), null, AppType.YGJ.getValue());
		}

		if (terminals.size() > 0) {
			result = 2;
		} else {

			// 判断手机号是否已经注册
			terminals = terminalMapper.queryTerminalByPhoneRegisted(terminal
					.getPhone().trim(), AppType.YGJ.getValue());
			if (terminals.size() > 0) 	{

				// 判断注册的手机号是否已经绑定设备码
				if (terminal.getBid() == 1) {
					if (terminals.get(0).getCode() == null
							|| terminals.get(0).getCode().trim() == "") {

						// 绑定设备码
						terminal.setId(terminals.get(0).getId());
						if (terminalMapper.updateTerminalById(terminal) > 0) {
							result = 1;
						} else {
							result = 0;
						}
					} else {
						result = 3;
					}
				} else {
					if (terminals.get(0).getAppleId() == null
							|| terminals.get(0).getAppleId().trim() == "") {

						// 绑定设备码
						terminal.setId(terminals.get(0).getId());
						if (terminalMapper.updateTerminalById(terminal) > 0) {
							result = 1;
						} else {
							result = 0;
						}
					} else {
						result = 3;
					}
				}

			} else {
				terminal.setStatus(1); // 设置状态码，默认为0（未通过）

				// 查询当前手机好是否在员工档案中已经存在，存在则在中间表中添加对应记录
				List<Employee> employees = employeeMapper
						.queryEmployeeByPhone(terminal.getPhone().trim());

				if (employees.size() > 0) {
					int bid = terminal.getBid();
					terminal.setBid(AppType.YGJ.getValue());
					if (terminalMapper.addTerminal(terminal) <= 0) {
						try {
							throw new Exception();
						} catch (Exception e) {
							// e.printStackTrace();
							return 0;
						}
					}

					if (bid == 1) {
						terminals = terminalMapper
								.queryTerminalByCodesRegisted(null, null,
										terminal.getCode(),
										AppType.YGJ.getValue());
					} else {
						terminals = terminalMapper
								.queryTerminalByCodesRegisted(null, terminal
										.getAppleId().trim(), null, AppType.YGJ
										.getValue());
					}

					// 员工档案中存在该手机号，设置更新员工档案的设备外键
					if (employeeMapper.updateEmployeeTerminalInfoById(employees
							.get(0).getId(), terminals.get(0).getId()) > 0) {
						result = 1;
						EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();
						IMUserAPI user = (IMUserAPI)factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
						BodyWrapper userBody = new IMUserBody(employees
								.get(0).getId() + "", "123456", employees
								.get(0).getName());
						user.createNewIMUserSingle(userBody);
					} else {
						try {
							throw new Exception();
						} catch (Exception e) {
							// e.printStackTrace();
							return 0;
						}
					}

					// }
					/*
					 * } else { // 新增微信设备 result =
					 * terminalMapper.addTerminal(terminal); }
					 */
				} else {
					return 0;
				}

			}

		}
		return result;
	}
	
	public static void main(String[] args) {
		EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();
		ChatGroupAPI chatGroupAPI = (ChatGroupAPI)factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
		String name = "青岛国际机场值班";
		String[] objects = new String[]{};

		BodyWrapper userBody = new ChatGroupBody(name, name, true, Long.valueOf("2000"), true, "1317", objects);
		System.out.println(chatGroupAPI.createChatGroup(userBody));
	}

}